<template>
  <div class="view_plan">
    <div class="title_head">
      <a-icon @click="goBack" type="left" />
      <div class="plan_status">{{ statusMap[status] }}</div>
      <div class="plan_title">{{ planName }}</div>
    </div>
    <a-tabs default-active-key="1" @change="changeTab">
      <a-tab-pane key="1" tab="数据详情" v-if="showCount"></a-tab-pane>
      <a-tab-pane key="2" tab="计划配置"></a-tab-pane>
    </a-tabs>
    <div v-show="showCount && curTab === '1'">
      <div class="query_form">
        <a-range-picker
          format="YYYY-MM-DD"
          v-model="date"
          :allowClear="false"
          @change="handlerQuery"
          :placeholder="['开始时间', '结束时间']"
        />
        <a-select v-model="type" @change="handlerQuery" style="margin-left: 20px;">
          <a-select-option :value="1">主要目标用户</a-select-option>
          <a-select-option :value="2">次要目标1用户</a-select-option>
          <a-select-option :value="3">次要目标2用户</a-select-option>
          <a-select-option :value="4">次要目标3用户</a-select-option>
        </a-select>
      </div>
      <div class="plan_chart" ref="plan_chart"></div>
    </div>
    <div v-show="curTab === '2'">
      <div class="content">
        <div class="left_con">
          <a-steps @change="changeStep" direction="vertical" :current="currentStep">
            <a-step title="触发条件" description="触发条件" />
            <a-step title="目标设置" description="设置运营计划的目标" />
          </a-steps>
        </div>
        <div class="right_con">
          <div v-show="currentStep === 0">
            <a-row>
            <a-form-item label="计划类型">
              <div class="plan_type_list">
                <div class="plan_type" :class="{ selected: formType === 0 }" >
                  <a-icon type="thunderbolt" theme="filled" />
                  <div>触发型-完成A</div>
                  <div class="selected_icon">
                    <div class="selected_rect"></div>
                    <a-icon class="selected_check" type="check" />
                  </div>
                </div>
                <div class="plan_type" :class="{ selected: formType === 1 }">
                  <a-icon type="thunderbolt" theme="filled" />
                  <div>触发型-完成A 未完成B</div>
                  <div class="selected_icon">
                    <div class="selected_rect"></div>
                    <a-icon class="selected_check" type="check" />
                  </div>
                </div>
              </div>
            </a-form-item>
          </a-row>
            <a-form-item>
              <slot name="label">
                <div>触发时间</div>
              </slot>
              <div style="background: #f5f8fc;padding: 12px;">
                <div class="flex">
                  <a-icon v-if="expand" @click="handerExpand" class="expand" type="up-square" />
                  <a-icon v-else @click="handerExpand" class="expand" type="down-square" />
                  在计划起止时间内完成下列事件后
                </div>
                <div v-show="expand">
                  <EventRule type="view" ref="eventRule" :projectId="projectId" />
                </div>
              </div>
              <div v-if="formType === 1" class="flex" style="margin-top: 20px;">
                  <div style="width: 30px;">且在</div>
                  <a-input-number v-model="windowTimes" style="width: 100px; margin: 0 10px;" />
                  <a-select v-model="windowUnit" style="width: 100px;margin-right: 10px;">
                    <a-select-option value="MINUTE">分钟</a-select-option>
                    <a-select-option value="HOUR">小时</a-select-option>
                    <a-select-option value="DAY">天</a-select-option>
                  </a-select>
                  <div>内</div>
              </div>
              <div style="background: #f5f8fc; margin-top: 20px;padding: 12px;" v-show="formType === 1">
                <div class="flex">
                  <a-icon v-if="expandB" @click="handerExpandB" class="expand" type="up-square" />
                  <a-icon v-else @click="handerExpandB" class="expand" type="down-square" />
                  未完成事件 B
                </div>
                <div v-show="expandB">
                  <EventRule type="view" ref="eventRuleB" :projectId="projectId" />
                </div>
              </div>
            </a-form-item>
            <div class="delay-row">
              <div>则</div>
              <a-form-item class="delay_input" label="">
                <a-select v-model="isdelay" disabled>
                  <a-select-option :value="0">立即</a-select-option>
                  <a-select-option :value="1">延迟</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item class="delay_input" v-if="isdelay===1" label="">
                <a-input-number v-model="delayTimes" disabled />
              </a-form-item>
              <a-form-item class="delay_input" v-if="isdelay===1" label="">
                <a-select v-model="delayUnit" disabled>
                  <a-select-option value="MINUTE">分钟</a-select-option>
                  <a-select-option value="HOUR">小时</a-select-option>
                  <a-select-option value="DAY">天</a-select-option>
                </a-select>
              </a-form-item>
              对受众用户进行触达
            </div>
            <a-form-item label="起止时间" style="width: 100%;">
              <a-range-picker
                :show-time="{ format: 'HH:mm' }"
                disabled
                v-model="scheduleDate"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始时间', '结束时间']"
              />
            </a-form-item>
            <a-form-item label="参与限制">
              <a-radio-group v-model="times" disabled>
                <a-radio :value="0">参与1次</a-radio>
                <a-radio :value="1">参与多次</a-radio>
              </a-radio-group>
            </a-form-item>
            <div v-if="times === 1">
              <a-form-item label="">
                同一个用户
                <a-input-number v-model="limitDay" disabled />
                自然日内，最多参与
                <a-input-number v-model="limitTimes" disabled />
                次
              </a-form-item>
            </div>
            <div v-if="times === 1">
              提示：当用户退出计划后，才可再次进入，点击查看<a href="">运营计划退出机制</a>
            </div>
            <div v-else>
              当前计划，同一用户仅参与 1 次
            </div>
          </div>
          <div v-show="currentStep === 1">
            <Target type="view" ref="target" :projectId="projectId" />
          </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import { baseMixin } from '@/store/app-mixin';
import moment from 'moment';
import EventRule from "./eventRule.vue";
import Target from "./target.vue";

export default {
    name: 'ViewPlan',
    mixins: [baseMixin],
    components: {
      EventRule,
      Target
    },
    data () {
      return {
        expand: true,
        expandB: true,
        type: 1,
        date: [moment(new Date(), 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')],
        showCount: false,
        planName: '',
        status: '',
        curTab: '1',
        currentStep: 0,
        projectId: '',
        formType: 0,
        times: 0,
        isdelay: 0,
        limitDay: 15,
        limitTimes: 1,
        scheduleDate: [],
        statusMap: {
          0: '草稿',
          1: '待审批',
          2: '运行中',
          3: '暂停',
          4: '已结束',
          5: '归档'
        }
      }
    },
    created() {
      this.projectId = this.$route.query.projectId;
    },
    mounted () {
      this.init();
    },
    methods: {
      ...mapActions('planManage', ['getPlanReport', 'getPlan']),
      init () {
        this.getPlan(this.$route.query).then(res => {
          if (res.code === 0) {
            const { name, status, scheduleStart, scheduleEnd, joinLimitRule, type, convertRule, triggerRule } = res.data;
            this.planName = name;
            this.status = status;

            this.scheduleDate = [moment(scheduleStart), moment(scheduleEnd)];
            this.date = [moment(scheduleStart), moment(scheduleEnd)];
            // if (status === 5) {
              this.showCount = true;
              this.getChartData();
            // } else {
            //   this.curTab = '2';
            // }
            this.formType = type;
            if (joinLimitRule !== '{}') {
              const joinLimitRuleObj = JSON.parse(joinLimitRule);
              this.limitTimes = joinLimitRuleObj.limit;
              this.limitDay = joinLimitRuleObj.value;
              this.times = 1;
            }
            
            const triggerRuleObj = JSON.parse(triggerRule);
            const { delay_config, pattern_first_do, pattern_then_not_do } = triggerRuleObj;
            if (delay_config.value) {
              this.isdelay = 1;
              this.delayTimes = delay_config.value;
              this.delayUnit = delay_config.unit;
            }

            if (this.formType === 1) {
              this.$refs.eventRule.setRuleData(pattern_first_do);
              this.$refs.eventRuleB.setRuleData(pattern_then_not_do);
            } else {
              this.$refs.eventRule.setRuleData(pattern_first_do);
            }

            const convertRuleObj = JSON.parse(convertRule);

            this.$refs.target.setRuleData(convertRuleObj);
          }
        });
      },
      changeTab(key) {
        this.curTab = key;
      },
      getChartData() {
        const queryParams = {
          type: this.type,
          ...this.$route.query,
          startDate: this.date[0].format('YYYY-MM-DD'), 
          endDate: this.date[1].format('YYYY-MM-DD')
        };
        this.getPlanReport(queryParams).then(res => {
          if (res.code === 0) {
            this.initChart(res.data);
          }
        });
      },
      handlerQuery() {
        this.getChartData();
      },
      initChart(data) {
        const dateArr = [];
        const convertedCountArr = [];
        const convertedRateArr = [];
        const triggeredCountArr = [];
        data.forEach(item => {
          dateArr.push(item.date);
          convertedCountArr.push(item.convertedCount);
          convertedRateArr.push(item.convertedRate);
          triggeredCountArr.push(item.triggeredCount);
        });

        const option = {
          title: {
            text: '趋势分析（人次）',
            // subtext: '最近一次触发日期2023-06-20'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['计划触发', '目标完成', '目标完成率'],
            bottom: 20,
          },
          grid: {
            left: '10%',
            right: '10%',
            bottom: '10%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: dateArr
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '计划触发',
              type: 'line',
              stack: 'Total',
              data: triggeredCountArr
            },
            {
              name: '目标完成',
              type: 'line',
              stack: 'Total',
              data: convertedCountArr
            },
            {
              name: '目标完成率',
              type: 'line',
              stack: 'Total',
              data: convertedRateArr
            },
          ]
        };
        this.chart = this.$echarts.init(this.$refs.plan_chart);
        this.chart.setOption(option);
      },
      goBack() {
        this.$router.history.go(-1);
      },
      changeStep(step) {
        this.currentStep = step;
      },
      handerExpand() {
        this.expand = !this.expand;
      },
      handerExpandB() {
        this.expandB = !this.expandB;
      },
    }
  }
</script>

<style scoped>
.view_plan {
  background: #fff;
  width: 100%;
  padding: 20px;
}
.title_head {
  display: flex;
  line-height: 30px;
  align-items: center;
}

.plan_status {
 background: rgba(240,240,240,.91);
 color: #8492a6;
 height: 30px;
 padding: 0 10px;
 margin-left: 10px;
}
.plan_title {
  font-size: 22px;
  color: #1f2d3d;
  margin-left: 10px;
}
.query_form {
  margin-top: 20px;
}

.plan_chart {
  height: 600px;
  margin-top: 30px;
}



.content {
    display: flex;
    margin-top: 20px;
  }

  .plan_type_list {
    display: flex;
  }

  .plan_type_list .anticon-thunderbolt{
    margin-top: 14px;
  }

  .plan_type {
    display: flex;
    border: 1px solid #999;
    border-radius: 4px;
    margin-right: 16px;
    padding: 0 30px;
    position: relative;
    overflow: hidden;
  }

  .plan_type.selected {
    color: #01bf8a;
    border-color: #01bf8a;
  }

  .selected_icon {
    position: absolute;
    display: none;
    right: 0;
    top: 0;
    color: #fff;
    height: 20px;
    line-height: 20px;
  }

  .selected_rect {
    background-color: #01bf8a;
    width: 40px;
    height: 20px;
    transform: rotate(30deg);
    position: absolute;
    right: -10px;
    top: -8px;
  }

  .selected_check {
    line-height: 20px;
    font-size: 12px;
    position: absolute;
    right: 0;
    top: 0;
  }

  .selected .selected_icon {
    display: block;
  }

  .left_con {
    width: 240px;
    box-shadow: 0 0 5px rgba(153,170,192,.17);
    padding: 16px;
  }

  .right_con {
    flex: 1;
    margin-left: 20px;
    box-shadow: 0 0 5px rgba(153,170,192,.17);
    padding: 16px;
  }

  .expand {
    cursor: pointer;
    margin-right: 5px;
  }

  .delay-row {
    display: flex;
    line-height: 40px;
  }

  .delay_input {
    margin: 0 5px;
  }

  .flex {
    display: flex;
    align-items: center;
  }
</style>